package com.plian.system.controller.szyd;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.CacheUtil;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.entity.nkgl.InternalManagement;
import com.plian.system.entity.szyd.TbImportantMatters;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.nkgl.IInternalManagementService;
import com.plian.system.service.szyd.ITbImportantMattersService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.nkgl.InternalManagementVO;
import com.plian.system.vo.szyd.TbImportantMattersVO;
import com.plian.system.wrapper.nkgl.InternalManagementWrapper;
import com.plian.system.wrapper.szyd.TbImportantMattersWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * 三重一大
 */
@Slf4j
@RestController
@RequestMapping("api/tbImportMatters")
@AllArgsConstructor
public class TbImportantMattersController extends BaseController {

    private ITbImportantMattersService iTbImportantMattersService;

    private TbImportantMattersWrapper tbImportantMattersWrapper;

    private FormWorkflowService formWorkflowService;

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("三重一大-提交")
    public R submit(@Valid @RequestBody TbImportantMatters tbImportantMatters) {
//        if (Optional.ofNullable(internalManagement.getStatus()).isPresent() &&
//                internalManagement.getStatus() != FormStatusConstant.STASH){
//            if (!iInternalManagementService.checkIsExisted(internalManagement.getId(), internalManagement.getCode())){
//                return new R(CustomCode.builder().message("单据编码已存在").code(1999).success(false).build());
//            }
//        }
        Boolean result = iTbImportantMattersService.submit(tbImportantMatters);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(tbImportantMatters.getId()),tbImportantMatters.getFormType(),processVariable);

        return result ? R.data(tbImportantMatters) : new R(CommonCode.FAIL);
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @LogOperation("三重一大-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>)pd.get("ids");
        return iTbImportantMattersService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<TbImportantMattersVO> detail(@Valid @RequestBody TbImportantMatters tbImportantMatters) {
        TbImportantMatters detail = iTbImportantMattersService.getOne(Condition.getQueryWrapper(tbImportantMatters));
        return R.data(tbImportantMattersWrapper.entityToVO(detail));
    }

    /**
     * 分页
     */
    @PostMapping("/list")
    public ListResult<TbImportantMattersVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }


        QueryWrapper<TbImportantMatters> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new TbImportantMatters()), entityList
        );

        TokenSearch<TbImportantMatters> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);

        if(StringUtils.isNotBlank(query.getKeyword())){
            queryWrapper.and(wrapper ->
                    wrapper.like("item_name", query.getKeyword())
                            .or()
                            .like("matter_content", query.getKeyword())
            );

        }

        IPage<TbImportantMatters> pages = iTbImportantMattersService.page(Condition.getPage(query), queryWrapper);
        List<TbImportantMattersVO> tbImportantMattersVOList = tbImportantMattersWrapper.entityToVO(pages.getRecords());
        ListResult<TbImportantMattersVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(tbImportantMattersVOList);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 导入
     */
    @PostMapping("/excelCoverImport")
    @ApiOperation(value = "导入", notes = "传入文件")
    @LogOperation("三重一大-导入")
    public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
//        String matterType=httpServletRequest.getParameter("matterType");
        String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
        CacheUtil.put("progress","progress",progressId + "#half:hour",0);
        InputStream inputStream = multipartFile.getInputStream();
        ServletRequestAttributes att = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(att, true);
        String token = att.getRequest().getHeader("token");
        att.setAttribute("token", token, RequestAttributes.SCOPE_SESSION);
        iTbImportantMattersService.importExcel(progressId, inputStream);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }
    @GetMapping("/progress/{progressId}")
    @ApiOperation(value = "获取导入进度", notes = "传入进程id")
    public ObjResult progress(@PathVariable String progressId){
        Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
        if(data != null && data instanceof String){
            if ("导入成功".equals(data)){
                ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
                PageData pd = new PageData();
                pd.put("data", 200);
                objResult.setPageData(pd);
                return objResult;
            }
            return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
        }
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("data", data);
        objResult.setPageData(pd);
        return objResult;
    }
    @GetMapping("/exportImportFile/{matterType}")
    @ApiOperation(value = "生成excel文件")
    public ObjResult export(@PathVariable String matterType){
        PageData pd = new PageData();
        pd.put("key", iTbImportantMattersService.export(matterType));
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(pd);
        return objResult;
    }
    /**
     * 下载excel文件 并删除
     *
     * @param key
     * @param response
     */
    @GetMapping("/download/{key}")
//    @PassToken
    public void download(@PathVariable String key, HttpServletResponse response) {
        iTbImportantMattersService.download(key, response);
    }
}
